﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraVerticalGrid.Events;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;

using System;
using System.Data;
using System.Drawing;

namespace ConfExpert.Forms.SatinAlma
{
    public partial class KstYukleme : XForm
    {
        int UreticiId;
        string xml;
        public KstYukleme(int UreticiId, string xml)
        {
            InitializeComponent();
            this.xml = xml;
            this.UreticiId = UreticiId;
            this.Text += " - " + AppSession.Lookups.Vendor.FindByVendorId(UreticiId).Name;
        }

        RepositoryItemComboBox RiTercih;
        void PrepareRiTercih()
        {
            RiTercih = new RepositoryItemComboBox();
            RiTercih.Items.AddRange(new object[] { "Evet", "" });
            RiTercih.TextEditStyle = TextEditStyles.DisableTextEditor;
        }

        private void KstYukleme_Load(object sender, EventArgs e)
        {

            gridView1.Init("GetKstYukleme", UreticiId, xml);

            PrepareRiTercih();
            gridView1.Columns["DevamiGelecek"].ColumnEdit = RiTercih;
            gridView1.MakeReadOnly("DevamiGelecek");

            gridView1.FormatAsNumber(1, "Mt", "YuklenenMt", "SonYukleme", "Fark");
            gridView1.AddSummary("Mt", "YuklenenMt", "SonYukleme", "Fark");
            gridView1.MakeColumnInvisible("idx");
            gridView1.OptionsView.EnableAppearanceEvenRow = false;
            gridView1.RowStyle += gridView1_RowStyle;
            gridView1.BestFitColumns();

            CreateVerticalGrid();

            bbiKaydet.Enabled = gridView1.DataTable().Rows.Count > 0;
            foreach (DataRow dr in gridView1.DataTable().Rows)
                bbiKaydet.Enabled &= (dr["ProductId"] != DBNull.Value);

            bbiKaydet.ItemClick += bbiKaydet_ItemClick;
        }

        void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (gridView1.GetRowCellValue(e.RowHandle, "DevamiGelecek").ToStr().StartsWith("E"))
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.LightBlue;   //LightGray;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView1.Appearance.EvenRow : gridView1.Appearance.OddRow);
        }

        RepositoryItemGridLookUpEdit riSM;
        void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            vgc.CloseEditor();

            if (gridView1.DataTable().Compute("SUM(YuklenenMt)", "ProductId is null").ToInt() > 0)
            {
                ShowErrorMessage("ProductId bütün satırlarda girilmiş olmalı!");
                return;
            }


            if ((
                (GetVal("FaturaNo") != null &&
                GetVal("FaturaTarihi") != null) ||
                (GetVal("IrsaliyeNo") != null &&
                GetVal("IrsaliyeTarihi") != null)) &&

                GetVal("GerShipMethodId") != null)
            {
                string str = gridView1.Serialize();  //!

                int res = ExecuteScalar("UpdKstYukleme2",
                    str,
                    UreticiId,
                    GetVal("GerShipMethodId").ToInt(),
                    GetVal("GerYuklemeTarihi").ToDate(),
                    GetVal("FaturaTarihi").ToDate(),
                    GetVal("FaturaNo").ToStr(),
                    GetVal("GerTeslimSekliId").ToInt(),
                    GetVal("IrsaliyeTarihi").ToDate(),
                    GetVal("IrsaliyeNo").ToStr(),
                    0
                    ).ToInt();

                if (res > 0)
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;

                else if (res < 0)
                    if (XtraMessageBox.Show("Bu belgeno.'ya ilişkin yükleme daha önce girilmiş. O yüklemeye eklemek ister misiniz?", "Teyid", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        ExecuteScalar("UpdKstYukleme2",
                            str,
                            UreticiId,
                            GetVal("GerShipMethodId").ToInt(),
                            GetVal("GerYuklemeTarihi").ToDate(),
                            GetVal("FaturaTarihi").ToDate(),
                            GetVal("FaturaNo").ToStr(),
                            GetVal("GerTeslimSekliId").ToInt(),
                            GetVal("IrsaliyeTarihi").ToDate(),
                            GetVal("IrsaliyeNo").ToStr(),
                            1
                            );

                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                //else
                //    ShowErrorMessage("Bu yükleme şekli bu üretici için tanımlı değil. Tanımlamalı veya legal değerlerden biriyle değiştirmelisiniz.");

            }
            else
                ShowErrorMessage("FaturaNo, FaturaTarihi ve YüklemeŞekli zorunlu alanlardır.");
        }

        BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        void CreateVerticalGrid()
        {
            DataTable dtSM = ExecuteDataTable("GetLegalShipMethods", UreticiId);
            riSM = RepositoryManager.GetGLESablon(dtSM, "Name", "ShipMethodId");

            vgc.Rows.AddRange(new BaseRow[] {            
                AddItem("GerShipMethodId", typeof(int), riSM),
                AddItem("GerYuklemeTarihi", typeof(DateTime)),
                AddItem("FaturaTarihi", typeof(DateTime)),
                AddItem("FaturaNo", typeof(string)),
                AddItem("GerTeslimSekliId", typeof(int), RI(Rp.TeslimSekliA)),
                AddItem("IrsaliyeTarihi", typeof(DateTime)),
                AddItem("IrsaliyeNo", typeof(string))
                
            });

            vgc.GetRowByFieldName("GerShipMethodId").Properties.Caption = "YüklemeŞekli";

            vgc.SetCellValue(vgc.Rows["GerYuklemeTarihi"], 0, DateTime.Today);
            if (dtSM.Rows.Count == 1)
                vgc.SetCellValue(vgc.Rows["GerShipMethodId"], 0, dtSM.Rows[0]["ShipMethodId"]);

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            vgc.BestFit();
            //vgc.GetRowByFieldName("Notlar").Height = 60;
        }

        private void dockPanel1_Click(object sender, EventArgs e)
        {

        }

    }
}
